package com.lzp.copyui.pvz

import android.content.Context
import android.graphics.BitmapFactory
import android.graphics.Canvas
import android.graphics.Rect
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.AttributeSet
import android.util.Log
import android.view.View
import com.lzp.copyui.R

/**
 * @description:
 * @author: lxp
 * @date: 2022/4/19 下午3:47
 */
class PVZView : View {
    /**
     * 每帧动画的间隔
     */
    private val dTime = 60

    private var current = 0

    private val itemWidth = 76
    private val itemHeight = 96

    private val marginWidth = 2
    private val marginHeight = 2
    private val bmp by lazy { BitmapFactory.decodeResource(context.resources, R.mipmap.pvz) }

    private var src = Rect()
    private var dst = Rect()

    private val handler = object : Handler(Looper.getMainLooper()) {
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            if (current >= 21) {
                current = 0
            } else {
                current++
            }
            invalidate()
            sendEmptyMessageDelayed(0, dTime.toLong())
        }
    }

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        start()
    }


    fun start() {
        handler.sendEmptyMessage(0)
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas?.let {
            val itemTop = if (current > 10) itemHeight + marginHeight else marginHeight
            val index = if (itemTop == marginHeight) current else current - 11
            val itemLeft = index * itemWidth + (index + 1) * marginWidth
            src.set(itemLeft, itemTop, itemLeft + itemWidth, itemTop + itemHeight)
            dst.set(0, 0, width, height)
            it.drawBitmap(bmp, src, dst, null)
        }
    }
}